package com.sec.android.app.myfiles.facade.cmd;

import android.content.Context;
import android.widget.Toast;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.dialog.SortbyDialogFragment;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.UiUtils;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

public class SetSortByCmd extends SimpleCommand {

    public static final String TAG_SORTBY = "sortby";

    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();
        AbsMyFilesFragment fragment = (AbsMyFilesFragment) params[0];
        Integer sortByType = (Integer) params[1];

        if (FileOperator.isWorking()) {
            Toast.makeText(fragment.context(), R.string.cant_perform_action, Toast.LENGTH_SHORT).show();
            return;
        }

        if (sortByType == null) {
            try {
                UiUtils.sendLocalBroadcastIntent(fragment.getContext(), AppConstants.DISMISS_DIALOG, fragment.getProcessId(), TAG_SORTBY);
                SortbyDialogFragment sortbyDialog = SortbyDialogFragment.getInstance();
                sortbyDialog.setTargetFragment(fragment, R.id.menu_sort_by);
                sortbyDialog.show(fragment.getFragmentManager(), TAG_SORTBY);
            } catch (IllegalStateException e) {
                Log.e(this, "IllegalStateException:" + e.toString());
            }
        } else {
            Context context = fragment.context();
            NavigationInfo curInfo = fragment.getNavigationInfo();
            PreferenceUtils.setSortByType(context, curInfo, sortByType);
            PreferenceUtils.setSortByOrder(context, curInfo, getOrder(context, curInfo));
            fragment.reload();
        }
    }

    private int getOrder(Context context, NavigationInfo curInfo) {
        int nCurOrder = PreferenceUtils.getSortByOrder(context, curInfo);
        int ret = AppConstants.SortByOrder.DESC;
        if (nCurOrder == AppConstants.SortByOrder.DESC) {
            ret = AppConstants.SortByOrder.ASC;
        }
        return ret;
    }
}
